package com.wangyu.talents.web.system.user.utils;

import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.wangyu.talents.common.config.Constants;
import com.wangyu.talents.web.system.resource.model.Resource;
import com.wangyu.talents.web.system.resource.service.ResourceService;
import com.wangyu.talents.web.system.role.model.Role;
import com.wangyu.talents.web.system.role.service.RoleService;
import com.wangyu.talents.web.system.user.model.User;
import com.wangyu.talents.web.system.user.service.UserService;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Component;

/**
 * @author wangyu
 * @Date 2018-09-04 23:43
 */
@Component
public class UserUtil {

  private static UserService userService = SpringUtil.getBean(UserService.class);
  private static RoleService roleService = SpringUtil.getBean(RoleService.class);
  private static ResourceService resourceService = SpringUtil.getBean(ResourceService.class);

  /**
   * 获取用户所拥有的角色
   */
  public static List<Role> getRoles(Long userId) {
    return roleService.findUserRoles(userId);
  }

  /**
   * 判断当前用户是否拥有角色
   */
  public static boolean hasRole(String roleIdentifier) {
    return SecurityUtils.getSubject().hasRole(roleIdentifier);
  }

  /**
   * 判断当前用户是否拥有角色
   */
  public static boolean hasAllRoles(Set<String> roleIdentifiers) {
    return SecurityUtils.getSubject().hasAllRoles(roleIdentifiers);
  }

  /**
   * 获取用户的角色标识符
   */
  public static Set<String> getRoleFlags(User user) {
    if (user != null) {
      List<Role> roles = UserUtil.getRoles(user.getId());
      //设置超级管理员权限
      if (user.getType() == 100) {
        return Sets.newHashSet("root", "admin");
      }

      if (roles != null) {
        return Sets.newHashSet(Collections2.transform(roles, new Function<Role, String>() {
          public String apply(Role input) {
            return input.getFlag();
          }
        }));
      }
    }
    return Sets.newHashSet();
  }

  /**
   * 获取用户的权限标识符 如sys:admin
   */
  public static Set<String> getPermissions(User user) {
    Set<String> permissions = Sets.newHashSet();

    if (user != null) {
      //设置超级管理员权限
      if (user.getType() == 100) {    //超级管理员
        permissions.add("*:*:*");
        return permissions;
      }

      List<Role> roles = UserUtil.getRoles(user.getId());
      if (roles != null) {
        List<Long> roleIds = Lists
            .newArrayList(Collections2.transform(roles, new Function<Role, Long>() {
              public Long apply(Role input) {
                return input.getId();
              }
            }));

        List<Map<String, Object>> rolePermissions = resourceService
            .findRolePermissions(roleIds.toArray(new Long[roleIds.size()]));
        for (Map<String, Object> map : rolePermissions) {
          String resFlag = (String) map.get("resourceFlag");
          String perFlag = (String) map.get("permissionFlag");

          permissions.add(resFlag + ":" + perFlag);
        }
      }
    }
    return permissions;
  }

  /**
   * 获取用户菜单
   */
  public static List<Resource> getMenu(User user) {
    List<Long> resIds = Lists.newArrayList();

    if (user.getType() == 100) {        //超级管理员
      return resourceService.getCascadeList();
    }

    List roles = UserUtil.getRoles(user.getId());
    if (roles != null) {
      List<Long> roleIds = Lists
          .newArrayList(Collections2.transform(roles, new Function<Role, Long>() {
            public Long apply(Role input) {
              return input.getId();
            }
          }));

      List<Map<String, Object>> rolePermissions = resourceService
          .findRolePermissions(roleIds.toArray(new Long[roleIds.size()]));
      resIds = Lists.newArrayList(
          Collections2.transform(rolePermissions, new Function<Map<String, Object>, Long>() {
            public Long apply(Map<String, Object> input) {
              return (Long) input.get("resourceId");
            }
          }));
    }

    List<Resource> resList = resourceService.findByIds(resIds.toArray(new Long[resIds.size()]));
    return resourceService.cascadeList(resList);
  }

  /**
   * 匹配密码
   */
  public static boolean matches(User user, String newPassword) {
    return user.getPassword().equals(userService.encryptPassword(newPassword, user.getSalt()));
  }

  /**
   * 获取当前登录用户--后台用户
   */
  public static User getLoginUser() {
    return (User) SecurityUtils.getSubject().getSession().getAttribute(Constants.LOGIN_USER);
  }

  /**
   * 刷新当前登录用户，当用户信息发生改变的时候--后台用户
   */
  public static void refreshLoginUser(User newUser) {
    SecurityUtils.getSubject().getSession().setAttribute(Constants.LOGIN_USER, newUser);
  }

  /**
   * 根据用户名获取用户
   */
  public static User findByUserName(String userName) {
    return userService.findByUserName(userName);
  }

  /**
   * 后台用户登录
   */
  public static User login(String userName, String password) {
    return userService.login(userName, password);
  }
}
